<template>
  <el-row :gutter="20">
    <el-col :span="6" :xs="24">
      <ContentWrap class="h-1/1">
        <el-calendar class="compact-calendar" v-model="today">
          <template #date-cell="{ data }">
            <div class="date-cell-container" @click="handleDateClick(data)">
              <p :class="data.isSelected ? 'is-selected' : ''">
                {{ data.day.split('-')[2] }}
              </p>
            </div>
          </template>
        </el-calendar>
      </ContentWrap>
    </el-col>
    <el-col :span="18" :xs="24">
      <ContentWrap>
        <div class="date-heard">
          <el-icon style="cursor: pointer" @click="changeDate(-1)">
            <ArrowLeftBold />
          </el-icon>
          <p>{{ formatDate(today, 'YYYY-MM-DD') }}</p>
          <el-icon style="cursor: pointer" @click="changeDate(1)">
            <ArrowRightBold />
          </el-icon>
          <!-- <el-button
            type="success"
            style="position: absolute; right: 20px"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['pplan:shift-record:export']"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button> -->
        </div>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="序号" align="center" width="80" type="index" />
          <el-table-column label="班次" align="center" prop="shiftDate">
            <template #default="scope">
              {{
                scope.$index === 0
                  ? '早班 07:00-14:00'
                  : scope.$index === 1
                  ? '中班 14:30-22:00'
                  : scope.$index === 2
                  ? '晚班 22:00-07:00'
                  : ''
              }}
            </template>
          </el-table-column>
          <el-table-column label="司机" align="center" prop="shiftDriver">
            <template #default="scope">
              <el-select
                v-model="scope.row.shiftDriver"
                placeholder="请选择司机"
                filterable
                class="!w-160px"
                @change="handleUserChange(scope.$index, 'shiftDriver', $event)"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="保障员" align="center" prop="shiftSupport">
            <template #default="scope">
              <el-select
                v-model="scope.row.shiftSupport"
                placeholder="请选择保障员"
                filterable
                class="!w-160px"
                @change="handleUserChange(scope.$index, 'shiftSupport', $event)"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="航机员" align="center" prop="shiftCrew">
            <template #default="scope">
              <el-select
                v-model="scope.row.shiftCrew"
                placeholder="请选择航机员"
                filterable
                class="!w-160px"
                @change="handleUserChange(scope.$index, 'shiftCrew', $event)"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { ShiftRecordApi, ShiftRecordVO } from '@/api/pplan/shiftrecord'
import { getSimpleAllUserList } from '@/api/system/user'
import ShiftRecordForm from './ShiftRecordForm.vue'
import { ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, watch } from 'vue'

/** 排班管理 列表 */
defineOptions({ name: 'ShiftRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ShiftRecordVO[]>([]) // 列表的数据
const currentShiftId = ref<number | null>(null) // 当前排班ID
const queryParams = reactive({
  shiftDate: undefined
})
const exportLoading = ref(false) // 导出的加载中

/** 当前日期 */
const today = ref(new Date())

/** 查询列表 */
const getList = async () => {
  // 在查询参数中添加当前选中的日期
  queryParams.shiftDate = formatDate(today.value, 'YYYY-MM-DD')
  loading.value = true
  try {
    const data = await ShiftRecordApi.getShiftRecord(queryParams)
    if (data) {
      currentShiftId.value = data.id
      list.value = data.shiftUsers
    } else {
      await createNewShift()
    }
  } catch (err) {
    list.value = []
  } finally {
    loading.value = false
  }
}

/** 创建新排班 */
const createNewShift = async () => {
  try {
    const shiftDate = formatDate(today.value, 'YYYY-MM-DD')
    // 创建三个班次的默认数据（早班、中班、晚班）
    const defaultUsers = [
      { shiftDriver: null, shiftSupport: null, shiftCrew: null },
      { shiftDriver: null, shiftSupport: null, shiftCrew: null },
      { shiftDriver: null, shiftSupport: null, shiftCrew: null }
    ]
    // 调用创建API
    const data = await ShiftRecordApi.createShiftRecord({
      shiftDate,
      shiftUsers: defaultUsers
    })
    // currentShiftId.value = data.id
    // list.value = defaultUsers
    getList()
  } catch (err) {}
}

/** 更新排班信息 */
const updateShiftRecord = async () => {
  if (!currentShiftId.value) {
    message.warning('未找到排班信息，无法更新')
    return
  }
  try {
    const shiftDate = formatDate(today.value, 'YYYY-MM-DD')
    const response = await ShiftRecordApi.updateShiftRecord({
      id: currentShiftId.value,
      shiftDate,
      shiftUsers: list.value
    })
  } catch (err) {}
}

/** 处理用户选择变化 */
const handleUserChange = (index: number, field: string, value: any) => {
  // 更新列表中的值
  if (list.value[index]) {
    list.value[index][field] = value
    // 调用更新方法
    updateShiftRecord()
  }
}

/** 查询用户精简列表 */
const userList = ref([])
const getUserList = async () => {
  try {
    const data = await getSimpleAllUserList()
    userList.value = data
  } catch (err) {
    console.error('获取用户列表失败:', err)
  }
}

/** 切换日期 */
const changeDate = (days: number) => {
  const newDate = new Date(today.value)
  newDate.setDate(newDate.getDate() + days)
  today.value = newDate
}

/** 点击日历日期 */
const handleDateClick = (data: any) => {
  today.value = new Date(data.day)
}

/** 切换月份/日期时重新查询 */
watch(
  () => today.value,
  (newDate, oldDate) => {
    const newDateStr = formatDate(newDate, 'YYYY-MM-DD')
    const oldDateStr = oldDate ? formatDate(oldDate, 'YYYY-MM-DD') : ''
    if (newDateStr !== oldDateStr) {
      getList()
    }
  },
  { deep: true }
)

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ShiftRecordApi.exportShiftRecord(queryParams)
    download.excel(data, '排班管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getUserList()
})
</script>
<style lang="scss" scoped>
.compact-calendar {
  ::v-deep .el-calendar-table .el-calendar-day {
    height: 40px;
    display: flex;
    justify-content: center;
    line-height: 40px;
    padding: 0px;
    cursor: pointer; // 添加鼠标指针样式，提示可点击
  }

  ::v-deep .el-calendar-table td {
    border: none !important;
  }

  ::v-deep .date-cell-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    // 即使点击边框区域也能触发事件
  }
  ::v-deep .is-selected {
    border: 1px solid #43a2ff;
    width: 100%;
    text-align: center;
    border-radius: 5px;
    background-color: rgba(67, 162, 255, 0.1); // 增加选中背景色
  }

  // 非本月日期样式
  ::v-deep .el-calendar-table__row .disabled {
    color: #c0c4cc;
  }
}
.date-heard {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 20px;
  p {
    font-size: 20px;
    font-weight: 700;
    margin: 0px 10px;
  }
}
</style>
